<template>
  <border title="消息查看" :close="true" w="750px" h="500px" @close="$emit('close')" x="calc(50% - 325px)" y="30%">
    <div class="msgPages">
      <!-- 左侧联系人列表 -->
      <div class="left">
        <div class="search-box">
          <el-input
            placeholder="搜索联系人"
            prefix-icon="el-icon-search"
            v-model="searchText"
            clearable
            size="small"
            @input="filterContacts">
          </el-input>
        </div>
        <div class="contact-list">
          <div
            class="row"
            :class="{ 'row_select': currentContact && currentContact.groupId === contact.groupId, 'has-unread': contact.unreadCount > 0 }"
            v-for="contact in filteredContacts"
            :key="contact.groupId"
            @click="selectContact(contact)">
            <i class="el-icon-user-solid icons" v-if="contact.grouptype === 'person'"/>
            <i class="el-icon-s-home icons" v-else/>
            <div class="center">
              <div class="h">
                <span>{{ contact.groupRealname }}</span>
                <span class="time">{{ formatLastTime(contact.lastTime) }}</span>
              </div>
              <div class="h">
                <span style="font-size: 12px;padding-left: 5px" class="last-msg">
                  {{ contact.lastMsg || '暂无消息' }}
                </span>
                <span
                  v-if="contact.unreadCount > 0"
                  class="unread-badge">
                  {{ contact.unreadCount > 99 ? '99+' : contact.unreadCount }}
                </span>
              </div>
            </div>
          </div>

          <!-- 无联系人时的提示 -->
          <div v-if="filteredContacts.length === 0" class="no-contacts">
            <i class="el-icon-chat-line-round"></i>
            <p>暂无消息记录</p>
          </div>
        </div>
      </div>

      <!-- 右侧消息查看区域 -->
      <div class="right" v-if="currentContact">
        <div class="chat-header">
          <div class="chat-info">
            <i class="el-icon-user-solid header-icon" v-if="currentContact.grouptype === 'person'"/>
            <i class="el-icon-s-home header-icon" v-else/>
            <span class="chat-name">{{ currentContact.groupRealname }}</span>
            <span class="chat-type">{{ currentContact.grouptype === 'person' ? '个人' : '群组' }}</span>
            <span v-if="currentContact.unreadCount > 0" class="unread-indicator">
              <i class="el-icon-message"></i>
              有{{ currentContact.unreadCount }}条未读消息
            </span>
          </div>
<!--          <div class="header-tip">-->
<!--            <i class="el-icon-info"></i>-->
<!--            <span>只读模式 - 仅可查看消息</span>-->
<!--          </div>-->
        </div>

        <div class="msgList" ref="msgList">
          <!-- 加载状态 -->
          <div v-if="loadingMessages" class="loading-messages">
            <i class="el-icon-loading"></i>
            <span>加载消息中...</span>
          </div>

          <!-- 消息列表 -->
          <div
            class="item"
            :class="msg.fromUserId === currentUser.id ? 'my-msg' : 'receive-msg'"
            v-for="msg in messages"
            :key="msg.id">

            <!-- 接收的消息 -->
            <template v-if="msg.fromUserId !== currentUser.id">
              <i class="el-icon-user-solid icons"/>
              <div class="center" style="margin-left: 5px;">
                <div class="h">
                  <span>{{ getContactName(msg.fromUserId) }}</span>
                  <span class="time">{{ formatTime(msg.creatorTime) }}</span>
                  <span v-if="msg.isRead === 0" class="unread-dot"></span>
                </div>
                <div class="d receive-bubble">
                  {{ msg.message }}
                </div>
              </div>
            </template>

            <!-- 发送的消息 -->
            <template v-else>
              <div class="center" style="margin-right: 5px;">
                <div class="h">
                  <span class="time">{{ formatTime(msg.creatorTime) }}</span>
                  <span>我</span>
                </div>
                <div class="d my-bubble">
                  {{ msg.message }}
                </div>
              </div>
              <i class="el-icon-user-solid icons"/>
            </template>
          </div>

          <!-- 无消息时的提示 -->
          <div v-if="!loadingMessages && messages.length === 0" class="no-messages">
            <i class="el-icon-chat-dot-round"></i>
            <p>暂无消息记录</p>
          </div>
        </div>

        <!-- 只读提示 -->
<!--        <div class="readonly-tip">-->
<!--          <i class="el-icon-view"></i>-->
<!--          <span>只读模式，无法发送消息</span>-->
<!--        </div>-->
      </div>

      <!-- 无选中联系人时的提示 -->
      <div class="no-chat" v-else>
        <div class="no-chat-content">
          <i class="el-icon-chat-dot-round"></i>
          <p>请选择一个联系人查看消息</p>
          <p class="sub-tip">点击左侧联系人列表查看消息记录</p>
        </div>
      </div>
    </div>
  </border>
</template>

<script>
import border from "@/views/formShortLink/border/index.vue";
import { queryMessages, markMessagesAsRead, groupsPersons, getUnreadMessages } from '@/api/message';
import { UserSettingInfo } from '@/api/permission/userSetting';

export default {
  name: "personMsgPage",
  components: { border },
  props: {
    msgData: {
      type: [String, Array, Object],
      default: null
    },
    groupId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 当前用户信息
      currentUser: null,
      // 消息加载状态
      loadingMessages: false,
      // 当前选中的联系人
      currentContact: null,
      // 消息列表
      messages: [],
      // 联系人列表
      contacts: [],
      // 过滤后的联系人列表
      filteredContacts: [],
      // 搜索文本
      searchText: '',
      // 轮询定时器
      pollTimer: null
    }
  },
  computed: {
    // 当前聊天对象ID
    currentChatId() {
      return this.currentContact ? this.currentContact.groupId : '';
    }
  },
  watch: {
    // 监听消息数据变化
    msgData: {
      handler(newVal) {
        this.processMsgData(newVal);
      },
      immediate: true
    },
    // 监听groupId变化
    groupId: {
      handler(newVal) {
        if (newVal) {
          this.processGroupId(newVal);
        }
      },
      immediate: true
    }
  },
  methods: {
    // 处理消息数据
    processMsgData(msgData) {
      if (!msgData) return;

      if (typeof msgData === 'string') {
        // 处理字符串情况 - 个人消息
        const contact = this.contacts.find(c => c.groupId === msgData);
        if (contact) {
          this.currentContact = contact;
          this.loadMessages();
        }
      } else if (Array.isArray(msgData)) {
        // 处理数组情况 - 群组消息
        const contact = this.contacts.find(c => c.groupId === this.groupId);
        if (contact) {
          this.currentContact = contact;
          this.loadMessages();
        }
      } else if (typeof msgData === 'object') {
        // 处理对象情况
        this.currentContact = msgData;
        this.loadMessages();
      }
    },

    // 处理群组ID
    processGroupId(groupId) {
      if (!this.currentContact && groupId) {
        const contact = this.contacts.find(c => c.groupId === groupId);
        if (contact) {
          this.currentContact = contact;
          this.loadMessages();
        }
      }
    },

    // 选择联系人
    async selectContact(contact) {
      this.currentContact = contact;

      // 加载消息历史
      await this.loadMessages();

      // 标记为已读
      if (contact.unreadCount > 0) {
        await this.markAsRead();
        // 更新未读计数
        contact.unreadCount = 0;
        this.filterContacts();
      }

      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
    deduplicateByGroupId(messages) {
      const result = [];
      const seen = new Map();

      // 按时间倒序排列，确保最新的消息在前面
      const sortedMessages = messages.sort((a, b) =>
        new Date(b.creatorTime) - new Date(a.creatorTime)
      );

      sortedMessages.forEach(msg => {
        if (msg.type === 'group') {
          // 使用 groupId + message 作为唯一键，避免相同消息被重复显示
          const key = `${msg.groupId}_${msg.message}_${msg.creatorTime}`;
          if (!seen.has(key)) {
            seen.set(key, true);
            result.push(msg);
          }
        } else {
          // 个人消息直接添加
          result.push(msg);
        }
      });

      // 恢复原始顺序
      return result.sort((a, b) =>
        new Date(a.creatorTime) - new Date(b.creatorTime)
      );
    },


    // 加载消息
    async loadMessages() {
      if (!this.currentContact || !this.currentUser) return;

      this.loadingMessages = true;
      try {
        console.log(typeof this.currentContact.groupId === 'string')
        const request = {
          fromUserId: this.currentUser.id,
          toUserId: this.currentContact.groupId,
          type: this.currentContact.grouptype
        };

        const response = await queryMessages(request);
        if (response.code === 200) {
          const processedMessages = this.deduplicateByGroupId(response.data || []);
          this.messages = processedMessages;
        } else {
          this.$message.error('加载消息失败: ' + (response.message || '未知错误'));
        }
      } catch (error) {
        console.error('加载消息错误:', error);
        this.$message.error('加载消息失败');
      } finally {
        this.loadingMessages = false;
      }
    },

    // 标记消息为已读
    async markAsRead() {
      if (!this.currentContact || !this.currentUser) return;

      try {
        const request = {
          fromUserId: this.currentContact.groupId,
          toUserId: this.currentUser.id
        };

        const response = await markMessagesAsRead(request);
        if (response.code === 200) {
          console.log('消息标记为已读成功');
        } else {
          console.error('标记已读失败:', response.message);
        }
      } catch (error) {
        console.error('标记已读错误:', error);
      }
    },

    // 获取联系人列表
    async getContacts() {
      try {
        const response = await groupsPersons();
        if (response.code === 200) {
          this.contacts = response.data || [];
          // 为每个联系人添加未读消息计数
          await this.updateUnreadCounts();
          this.filteredContacts = [...this.contacts];
        } else {
          this.$message.error('获取联系人列表失败');
        }
      } catch (error) {
        console.error('获取联系人错误:', error);
        this.$message.error('获取联系人列表失败');
      }
    },

    // 更新未读消息计数
    async updateUnreadCounts() {
      if (!this.currentUser) return;

      try {
        const response = await getUnreadMessages(this.currentUser.id);
        if (response.code === 200) {
          const unreadMessages = response.data || [];

          // 重置所有联系人的未读计数
          this.contacts.forEach(contact => {
            contact.unreadCount = 0;
          });

          // 统计每个联系人的未读消息数
          unreadMessages.forEach(msg => {
            const contact = this.contacts.find(c =>
              (msg.groupId && c.groupId === msg.groupId) ||
              (!msg.groupId && c.groupId === msg.fromUserId)
            );
            if (contact) {
              contact.unreadCount++;
            }
          });

          this.filterContacts();
        }
      } catch (error) {
        console.error('更新未读消息计数错误:', error);
      }
    },

    // 过滤联系人
    filterContacts() {
      if (!this.searchText) {
        this.filteredContacts = [...this.contacts];
      } else {
        const searchLower = this.searchText.toLowerCase();
        this.filteredContacts = this.contacts.filter(contact =>
          contact.groupRealname.toLowerCase().includes(searchLower)
        );
      }
    },

    // 获取当前用户信息
    getCurrentUserInfo() {
      UserSettingInfo().then(res => {
        this.currentUser = res.data;
        // 用户信息获取后，获取联系人列表
        this.getContacts();
      }).catch(error => {
        console.error('获取用户信息失败:', error);
      });
    },

    // 获取联系人名称
    getContactName(userId) {
      const contact = this.contacts.find(c => c.groupId === userId);
      return contact ? contact.groupRealname : '用户' + (userId ? userId.substring(0, 4) : '');
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return '';

      try {
        const date = new Date(time);
        if (isNaN(date.getTime())) return '';

        const now = new Date();

        // 如果是今天
        if (date.toDateString() === now.toDateString()) {
          return date.toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit'
          });
        }

        // 如果是昨天
        const yesterday = new Date(now);
        yesterday.setDate(yesterday.getDate() - 1);
        if (date.toDateString() === yesterday.toDateString()) {
          return '昨天 ' + date.toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit'
          });
        }

        // 其他情况显示完整时间
        return date.toLocaleString('zh-CN', {
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });
      } catch (error) {
        console.error('时间格式化错误:', error);
        return '';
      }
    },

    // 格式化最后消息时间
    formatLastTime(time) {
      if (!time) return '';
      return this.formatTime(time);
    },

    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.msgList;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    },

    // 轮询更新消息和未读计数
    startPolling() {
      this.pollTimer = setInterval(async () => {
        if (this.currentUser) {
          // 更新未读消息计数
          await this.updateUnreadCounts();

          // 如果当前有选中的联系人，更新消息列表
          if (this.currentContact) {
            await this.loadMessages();
          }
        }
      }, 5000); // 每5秒轮询一次
    }
  },
  mounted() {
    this.getCurrentUserInfo();
    this.startPolling();
  },
  beforeDestroy() {
    if (this.pollTimer) {
      clearInterval(this.pollTimer);
    }
  }
}
</script>

<style scoped lang="scss">
.msgPages {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 100%;

  .left {
    width: 350px;
    border-right: 1px solid #DCDFE6;
    padding: 10px;
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .search-box {
      margin-bottom: 10px;
    }

    .contact-list {
      flex: 1;
      overflow-y: auto;

      .row {
        display: flex;
        flex-direction: row;
        padding: 12px 8px;
        border-radius: 8px;
        cursor: pointer;
        position: relative;
        transition: all 0.3s;
        margin-bottom: 2px;
        border: 1px solid transparent;

        &:hover {
          background-color: #f5f7fa;
          border-color: #c6e2ff;
        }

        // 有未读消息的样式
        &.has-unread {
          background-color: #fff2f0;
          border-color: #ffccc7;

          &:hover {
            background-color: #ffece8;
            border-color: #ffa39e;
          }
        }

        .icons {
          font-size: 36px;
          color: #409EFF;
          margin-right: 10px;
          align-self: flex-start;
        }

        .center {
          display: flex;
          flex-direction: column;
          flex: 1;
          min-width: 0;

          .h {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 4px;

            span:first-child {
              font-weight: 600;
              font-size: 14px;
              color: #303133;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }

            .time {
              font-size: 11px;
              color: #909399;
              flex-shrink: 0;
            }
          }

          .last-msg {
            font-size: 12px;
            color: #606266;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 180px;
          }

          .unread-badge {
            background-color: #F56C6C;
            color: white;
            border-radius: 10px;
            min-width: 18px;
            height: 18px;
            font-size: 11px;
            text-align: center;
            line-height: 18px;
            padding: 0 4px;
            flex-shrink: 0;
            animation: pulse 2s infinite;
          }
        }
      }

      .row_select {
        background-color: #EBF6FF;
        border-color: #91d5ff;

        &:hover {
          background-color: #EBF6FF;
        }
      }

      .no-contacts {
        text-align: center;
        color: #909399;
        padding: 40px 0;

        i {
          font-size: 48px;
          margin-bottom: 16px;
          display: block;
        }

        p {
          font-size: 14px;
        }
      }
    }
  }

  .right {
    display: flex;
    flex-direction: column;
    flex: 1;
    position: relative;
    height: 100%;

    .chat-header {
      padding: 12px 20px;
      border-bottom: 1px solid #DCDFE6;
      background: white;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .chat-info {
        display: flex;
        align-items: center;

        .header-icon {
          font-size: 24px;
          color: #409EFF;
          margin-right: 8px;
        }

        .chat-name {
          font-weight: 600;
          font-size: 16px;
          margin-right: 8px;
        }

        .chat-type {
          background: #409EFF;
          color: white;
          padding: 2px 6px;
          border-radius: 4px;
          font-size: 12px;
          margin-right: 12px;
        }

        .unread-indicator {
          background: #F56C6C;
          color: white;
          padding: 4px 8px;
          border-radius: 4px;
          font-size: 12px;
          display: flex;
          align-items: center;

          i {
            margin-right: 4px;
          }
        }
      }

      .header-tip {
        display: flex;
        align-items: center;
        font-size: 12px;
        color: #909399;

        i {
          margin-right: 4px;
        }
      }
    }

    .msgList {
      flex: 1;
      overflow-y: auto;
      padding: 20px;
      background: #f5f7fa;
      position: relative;

      .loading-messages {
        text-align: center;
        color: #909399;
        padding: 20px;

        i {
          margin-right: 8px;
        }
      }

      .item {
        display: flex;
        margin-bottom: 16px;
        position: relative;

        &.my-msg {
          justify-content: flex-end;
        }

        .icons {
          font-size: 36px;
          color: #409EFF;
          align-self: flex-start;
        }

        .center {
          max-width: 70%;

          .h {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 6px;

            span {
              font-size: 13px;
              color: #909399;
            }

            .time {
              font-size: 11px;
            }

            .unread-dot {
              width: 8px;
              height: 8px;
              background: #F56C6C;
              border-radius: 50%;
              margin-left: 6px;
              animation: pulse 2s infinite;
            }
          }

          .d {
            padding: 12px 16px;
            border-radius: 8px;
            line-height: 1.5;
            word-break: break-word;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
            position: relative;

            &.receive-bubble {
              background-color: white;
              border-top-left-radius: 2px;
            }

            &.my-bubble {
              background: #EBF6FF;
              border-top-right-radius: 2px;
            }
          }
        }
      }

      .no-messages {
        text-align: center;
        color: #909399;
        padding: 60px 0;

        i {
          font-size: 48px;
          margin-bottom: 16px;
          display: block;
        }

        p {
          font-size: 14px;
        }
      }
    }

    .readonly-tip {
      background: #f0f2f5;
      border-top: 1px solid #DCDFE6;
      padding: 12px 20px;
      text-align: center;
      color: #909399;
      font-size: 13px;

      i {
        margin-right: 6px;
      }
    }
  }

  .no-chat {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f7fa;

    .no-chat-content {
      text-align: center;
      color: #909399;

      i {
        font-size: 64px;
        margin-bottom: 16px;
        display: block;
        color: #DCDFE6;
      }

      p {
        font-size: 16px;
        margin-bottom: 8px;
      }

      .sub-tip {
        font-size: 14px;
        color: #C0C4CC;
      }
    }
  }
}

// 脉冲动画
@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 1;
  }
}

// 滚动条样式
.contact-list::-webkit-scrollbar,
.msgList::-webkit-scrollbar {
  width: 6px;
}

.contact-list::-webkit-scrollbar-track,
.msgList::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.contact-list::-webkit-scrollbar-thumb,
.msgList::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.contact-list::-webkit-scrollbar-thumb:hover,
.msgList::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
